<?php

require_once ROOT_PATH . 'lib/aip_sdk/AipOcr.php';
require_once ROOT_PATH . 'lib/aip_sdk/AipImageClassify.php';


class ImageHanler
{
    // 允许的图片类型
    const ALLOW_IMAGE_TYPES = [
        'jpeg', 'jpg', 'png', 'bmp'
    ];

    /**
     * 文字识别
     * @param $file_info 图片信息
     * @param string $upload_path  上传图片地址
     * @param int $type      类型
     * @return mixed
     * @throws Exception
     */
    public static function handleOcr($file_info, $upload_path, $type)
    {
        // 校验并获取图片信息
        $image = self::_validate_image($file_info, $upload_path);

        // 加上配置：开启检测图像朝向
        $options["detect_direction"] = "true";

        // 如果是身份证识别则判断参数
        if ($type === 4) {
            $id_card_side = $_POST['id_card_side'];
            if (empty($id_card_side) || !in_array($id_card_side, ['front', 'back'])) {
                throw new Exception('参数错误');
            }
            $options['id_card_side'] = $id_card_side;
        }

        // 文字识别
        $res = self::wordsOcr($image, $type, $options);

        // 返回格式的处理
        $result = handleResult($type, $res);

        if (empty($result)) {
            throw new Exception('识别错误');
        }

        return $result;
    }

    /**
     * 图像识别
     * @param $file_info 图片信息
     * @param string $upload_path  上传图片地址
     * @param int $type      类型
     * @return mixed
     * @throws Exception
     */
    public static function handleImage($file_info, $upload_path, $type)
    {
        // 校验并获取图片信息
        $image = self::_validate_image($file_info, $upload_path);

        // 图像识别
        $res = self::ImageRecogn($image, $type);

        $result = $res['result'];

        if (empty($result)) {
            throw new Exception('识别错误');
        }

        return $result;
    }

    /**
     * 文字识别
     * @param $image
     * @param int $type
     * @param array $options 配置
     * @return array
     * @throws Exception
     */
    public static function wordsOcr($image, $type = 1, $options = [])
    {
        $client = new AipOcr(APPID, APIKEY, SECRETKEY);

        $types = range(1, 10);
        if (!in_array($type, $types)) {
            throw new Exception('请求错误');
        }

        switch ($type) {
            // 调用通用文字识别, 图片参数为本地图片
            case 1:
                $res = $client->basicGeneral($image, $options);
                break;
            // 调用通用文字识别（高精度版）
            case 2:
                $res = $client->basicAccurate($image, $options);
                break;
            // 网络图片文字识别
            case 3:
                $res = $client->webImage($image, $options);
                break;
            // 身份证识别
            case 4:
                $id_card_side = $options['id_card_side'];
                $res = $client->idcard($image, $id_card_side, $options);
                break;
            // 银行卡识别
            case 5:
                $res = $client->bankcard($image);
                break;
            // 驾驶证识别
            case 6:
                $res = $client->drivingLicense($image, $options);
                break;
            // 行驶证识别
            case 7:
                $res = $client->vehicleLicense($image, $options);
                break;
            // 车牌识别
            case 8:
                $res = $client->licensePlate($image);
                break;
            // 营业执照识别
            case 9:
                $res = $client->businessLicense($image);
                break;
            // 通用票据识别
            case 10:
                $res = $client->receipt($image, $options);
                break;
            default:
                $res = [];
                break;
        }

        return $res;
    }

    /**
     * 图像识别
     * @param $image
     * @param int $type
     * @return array
     * @throws Exception
     */
    public static function ImageRecogn($image, $type = 1)
    {
        $client = new AipImageClassify(APPID, APIKEY, SECRETKEY);

        $types = range(1, 5);
        if (!in_array($type, $types)) {
            throw new Exception('请求错误');
        }

        switch ($type) {
            // 调用菜品识别
            case 1:
                $res = $client->dishDetect($image);
                break;
            // 调用车辆识别
            case 2:
                $res = $client->carDetect($image);
                break;
            // 调用logo商标识别
            case 3:
                $res = $client->logoSearch($image);
                break;
            // 调用动物识别
            case 4:
                $res = $client->animalDetect($image);
                break;
            // 调用植物识别
            case 5:
                $res = $client->plantDetect($image);
                break;
            default:
                $res = [];
                break;
        }

        return $res;
    }

    /**
     * 校验参数、上传图片和获取图片信息
     * @param $file_info
     * @param $upload_path
     * @return false|string
     * @throws Exception
     */
    private static function _validate_image($file_info, $upload_path)
    {
        // 判断请求方式
        if (!isPost()) {
            throw new Exception('请求方式错误');
        }

        // 判断图片是否正确，如正确则上传图片
        $upload_img_url = uploadFile($file_info, $upload_path, self::ALLOW_IMAGE_TYPES);

        // 读取图片信息
        return file_get_contents($upload_img_url);
    }
}